#include"lars_api.h"
#include<pthread.h>

struct ID{
    int t_id;   // 线程ID

    int modid;
    int cmdid;
};              // 每个线程访问的modid和cmdid不同

void *test_qps(void *args){

    // 拿出形参
    ID *id = (ID *)args;
    int modid = id->modid;
    int cmdid = id->cmdid;

    lars_client api;

    int ret;
    std::string ip;
    int port;

    // 记录qps记录
    long qps = 0;
    long last_time = time(NULL);

    long total_qps = 0;
    long total_time_second = 0;

    // 进行注册
    ret = api.reg_init(modid, cmdid);
    if(ret == 0 || ret == 3){
        // 进行qps测试
        while(1){
            // 获取host信息
            ret = api.get_host(modid, cmdid, ip, port);
            if(ret == 0){
                qps++;
                
                // 根据之前之前host使用的情况上报对应的成功host情况
                api.report_host(modid, cmdid, ip, port, 0);
            }
            else if(ret == 1){
                qps++;
                
                // 根据之前之前host使用的情况上报对应的失败host情况
                api.report_host(modid, cmdid, ip, port, 1);
            }
            else if(ret == 3){
                qps++;
            }
            else{
                // 此时是系统出现错误的情况
                printf("modid:%d, cmdid:%d system error\n", modid, cmdid);
            }

            if((time(NULL) - last_time) >= 1){
                // 计算qps
                total_time_second++;
                total_qps += qps;
                printf("thread:%d qps:[%ld]  average:[%ld]\n", id->t_id, qps, total_qps/total_time_second);                
                
                // 重置qps
                qps = 0;
                
                // 重置时间
                last_time = time(NULL);
            }
        }
    }
    else if(ret == 2){
        fprintf(stderr, "system error:%d\n",ret);
    }
    

    return NULL;
}

// 开发者业务模块
int main(int argc, char* argv[]){
    if(argc != 2){
        printf("usage: ./qps [thread_num]\n");
        return 1;
    }

    int num = atoi(argv[1]);

    struct ID *ids = new struct ID[num];

    pthread_t *tids = new pthread_t[num];

    for(int i=0; i<num; i++){
        ids[i].t_id = i;
        ids[i].modid = 1;
        ids[i].cmdid = i+1;

        pthread_create(&tids[i], NULL, test_qps, &ids[i]);

    }

    for(int i=0; i<num; i++){
        pthread_join(tids[i], NULL);
    }


    return 0;
}
